package src.main.java.com.pms.gui.dialog.sale;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import src.main.java.com.pms.service.SaleService;

public class SetSaleDialog extends JDialog {
    private JTextField petIdField;
    private JTextField priceField;
    private JTextField contactField;
    private SaleService saleService;

    public SetSaleDialog(JFrame parent) {
        super(parent, "设置寄卖", true);
        saleService = new SaleService();
        initComponents();
        setVisible(true); // 显示对话框
        petIdField.requestFocusInWindow(); // 确保宠物ID输入框获得焦点
    }

    private void initComponents() {
        setSize(400, 200);
        setLocationRelativeTo(getParent());

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));

        JLabel petIdLabel = new JLabel("宠物ID:");
        petIdField = new JTextField();

        JLabel priceLabel = new JLabel("期望价格:");
        priceField = new JTextField();

        JLabel contactLabel = new JLabel("卖家联系方式:");
        contactField = new JTextField();

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new SaveActionListener());

        panel.add(petIdLabel);
        panel.add(petIdField);
        panel.add(priceLabel);
        panel.add(priceField);
        panel.add(contactLabel);
        panel.add(contactField);
        panel.add(new JLabel());
        panel.add(saveButton);

        add(panel);
    }

    private class SaveActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int petId = Integer.parseInt(petIdField.getText().trim());
                double price = Double.parseDouble(priceField.getText().trim());
                String contact = contactField.getText().trim();

                if (petId <= 0 || price <= 0 || contact.isEmpty()) {
                    JOptionPane.showMessageDialog(SetSaleDialog.this, "请输入有效的信息", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                saleService.setPetForSale(petId, price, contact);
                JOptionPane.showMessageDialog(SetSaleDialog.this, "寄卖设置成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(SetSaleDialog.this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}
